package cn.bs.securitystudy.filter;

import cn.bs.securitystudy.util.JwtUtil;
import cn.bs.securitystudy.util.RedisUtil;
import cn.bs.securitystudy.vo.UserLogin;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        //如果token为空就不让它执行if下面的代码了
        if (StringUtils.isEmpty(token)) {
            //放行
            //这里放行过后,后面还有filterSercurityInterceptor过滤器会去判断是否认证
            filterChain.doFilter(request, response);
            //不让没通过filterSercurityInterceptor过滤器的请求再次去执行下面的代码,所以return
            return;
        }
        //解析token
        String userid;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            throw new RuntimeException("不是真正的token");
        }
        //从redis中获取用户信息
        String reidsKey = "login:" + userid;
        UserLogin userLogin = (UserLogin) redisUtil.get(reidsKey);
        if(Objects.isNull(userLogin)){
            throw new RuntimeException("你还没有登录");
        }
        //把用户信息存入SecurityContextHolder
        //这里还是用Username..这个东西来封装成Authentication对象,不过和之前的只传账号,密码不一样,这里选择的是三个参数的重载方法
        //好处在于,三个参数的方法最后会给把认证改成true,点源代码就能看见
        UsernamePasswordAuthenticationToken userToken = new UsernamePasswordAuthenticationToken(
                userLogin,null
                //权限信息还没有获取,所以现在先传个null
                //todo 给权限
                , userLogin.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(userToken);
        //放行
        filterChain.doFilter(request, response);


    }

}
